package com.iteaj.iot.boot.autoconfigure;

import com.iteaj.iot.boot.core.IotJdbcProperties;
import com.iteaj.iot.tools.db.rdbms.RdbmsHandle;
import com.iteaj.iot.tools.db.rdbms.RdbmsHandleProxyMatcher;
import com.iteaj.iot.tools.db.rdbms.DefaultRdbmsSqlManager;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@ConditionalOnBean(RdbmsHandle.class)
public class IotRdbmsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = {"rdbmsDataSource"})
    public Object rdbmsDataSource(IotJdbcProperties properties) {
        if(properties.getDatasource() == null) {
            throw new BeanCreationException("未配置数据源[iot.jdbc.datasource.xx]");
        }

        return RdbmsHandle.databaseSource.rdbmsDataSource = properties.getDatasource().build();
    }

    /**
     * 关系型数据库数据采集管理
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(DefaultRdbmsSqlManager.class)
    public DefaultRdbmsSqlManager rdbmsManager(@Qualifier("rdbmsDataSource") Object rdbmsDataSource) {
        return new DefaultRdbmsSqlManager((DataSource) rdbmsDataSource);
    }

    /**
     * 关系型数据库采集代理
     * @param rdbmsSqlManager
     * @return
     */
    @Bean
    public RdbmsHandleProxyMatcher rdbmsProtocolHandleProxyMatcher(DefaultRdbmsSqlManager rdbmsSqlManager) {
        return new RdbmsHandleProxyMatcher(rdbmsSqlManager);
    }
}
